/**
 * Created by Dalyn on 2017/3/13.
 * 企业端-交易记录
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {DatePicker,Table} from 'antd';
import OrderTradeListMutation from "./mutation/OrderTradeListMutation"
import Util from "../../util/Util"
import Pagination from "./Pagination"
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import "./css/orderTradeList.css";
import "./css/account_common.css";

/*导出组件*/
export default class OrderTradeList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            listInfo: [],
            /*总共多少条*/
            totalResult: "",
            /*每页条数*/
            pageItem: "",
            /*指定页码*/
            pageNum: 1,
            /*指定每页显示条数*/
            pageSize: 10,
            /*0-未完成，1-已完成*/
            status: "",
            /*合同编号*/
            contractId:"",
			/*查询起始日期,startValue记录格式转换前*/
			startDate:null,
			startValue:null,
			/*查询结束日期,endValue记录格式转换前*/
			endDate:null,
			endValue:null,
            /*后台错误提示*/
            hint: "",
            loading:true,
            enid:sessionStorage.getItem('enterpriseId'),
        };
        this.style = {
            confirm: {
                display:"inline-block",
                width: '90px',
                height: '28px',
                lineHeight:"28px",
                textAlign:"center",
                backgroundColor: "#f7f5f5",
                fontSize: "14px",
                color: "#333333",
                fontFamily: "Microsoft YaHei",
                border:"1px solid #ededed",
                borderRadius: "2px",
                marginLeft: "20px",
                userSelect:"none",
                cursor:"pointer",
            },
            confirm_active: {
                display:"inline-block",
                width: '90px',
                height: '28px',
                lineHeight:"28px",
                textAlign:"center",
                backgroundColor: "#36b3b3",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "2px",
                marginLeft: "20px",
                userSelect:"none",
                cursor:"pointer",
            },
            page_ensure:{
                fontSize: "12px",
                color: "#999",
                fontFamily: "Microsoft YaHei",
                border:"1px solid #ededed",
                borderRadius: "2px",
                marginLeft: "10px",
                width: '40px',
                height: '22px',
                backgroundColor: "white",
            },
            input: {
                width: "200px",
                height: "28px",
            },
        };
    }

    componentWillMount() {
        this.myRelay();
    }

    myRelay() {
        Relay.Store.commitUpdate(
            new OrderTradeListMutation({
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                status: this.state.status,
                contractId:this.state.contractId,
                startDate:this.state.startDate,
                endDate:this.state.endDate,
                enId:this.state.enid
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.orderTradeList.orderTradeList;
                    // console.log(data)
                    if (data.errorCode === "0") {
                        this.setState({
                            listInfo: data.orders,
                            totalResult: data.totalResult,
                            pageItem: data.orders.length
                        },()=>{
                            this.setState({ loading: false });
                            this.refs.pagination.setState({
                                text:this.state.pageNum,
                            })
                        });
                    } else {
                        this.setState({
                            hint: data.value,
                        });
                    }
                }

            }
        );
    }
    /*全部*/
    whole() {
        this.refs.search.setState({
            text:"",
        });
        this.setState({
            status:"",
            pageNum:"1",
            loading:true,
            contractId:"",
        },this.myRelay);
    }

    /*未完成*/
    pending() {
        this.refs.search.setState({
            text:"",
        });
        this.setState({
            status: "3",
            pageNum:"1",
            loading:true,
            contractId:"",
        }, this.myRelay);
    }

    /*已完成*/
    already() {
        this.refs.search.setState({
            text:"",
        });
        this.setState({
            status: "4",
            pageNum:"1",
            loading:true,
            contractId:"",
        }, this.myRelay);
    }

    /*模糊搜索*/
    search() {
        this.setState({
            contractId: this.refs.search.state.text,
            pageNum: "1",
            pageSize: this.state.pageSize,
        }, this.myRelay);
    }
    /*页面表单失去焦点时*/
    bluron(type) {
        switch (type) {
            case "search":
                this.setState({
                    contractId: this.refs.search.state.text,
                });
                return;
            case "page":
                this.setState({
                    pageNum: this.refs.page.value == "" ? "1" : this.refs.page.value,
                });
                return;
        }
    }
    /*获取焦点*/
    focuson(type){
        switch (type){
            case "search":
                this.setState({
                    contractId: this.refs.search.state.text
                });
                return;
        }
    }

    /*页码*/
    onSure(size,num){
        this.setState({
            pageSize: size,
            pageNum: num,
            loading:true,
        }, this.myRelay)
    }
	/*搜索起始时间*/
	setStartDate(date) {
		////console.log(!date);
		if (!date) {
			this.setState({
				startDate: null,
				startValue:null
			}, this.myRelay);
		}else{
			this.setState({
				startDate: date.format('YYYY-MM-DD'),
				startValue:date
			}, this.myRelay);
		}
    }

	/*搜索结束时间*/
	setEndDate(date) {
		if (!date) {
			 this.setState({
				endDate: null,
				endValue:null
			}, this.myRelay);
		}else{
			 this.setState({
				endDate: date.format('YYYY-MM-DD'),
				endValue:date
			}, this.myRelay);
		}
    }

	/*限制起始日期必须小于结束日期*/
	disabledStartDate = (startDate) => {
		const endDate = this.state.endValue;
		//console.log(endDate)
		if (!startDate || !endDate) {
			return false;
		}
		return startDate.valueOf() > endDate.valueOf();
	  }

	/*限制结束日期必须大于等于起始日期*/
	disabledEndDate = (endDate) => {
		const startDate = this.state.startValue;
		if (!startDate || !endDate) {
			return false;
		}
		return endDate.valueOf() <= startDate.valueOf();
	}

	render() {
        const columns = [
            {
                title: '日期',
                dataIndex: 'createDate',
                key: 'createDate',
                render: (text, record) => {
                    return (
                        <span>{Util.dateFormat(record.createDate)}</span>
                    )
                }
            }, {
                title: '销售合同',
                dataIndex: 'signedContract',
                key: 'signedContract',
                render: (text, record) => {
                    return (
                        <span title={record.signedContract == null ?"无":record.signedContract}>{record.signedContract == null ?"无":record.signedContract}</span>
                    )
                }
            }, {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (text, record) => {
                    return (
                        <span>{record.status == 4 ? "已完成" : "未完成"}</span>
                    )
                }
            }, {
                title: '销售金额（元）',
                dataIndex: 'account',
                key: 'account',
                render: (text, record) => {
                    return (
                        <span>{Util.doubleFormat(parseFloat(record.account/100).toFixed(2))}</span>
                    )
                }
            }, {
                title: '采购金额（元）',
                dataIndex: 'purchaseAccount',
                key: 'purchaseAccount',
                render: (text, record) => {
                    return (
                        <span>{Util.doubleFormat(parseFloat(record.purchaseAccount/100).toFixed(2))}</span>
                    )
                }
            },{
                title: '毛利',
                dataIndex: 'profitAccount',
                key: 'profitAccount',
                render: (text, record) => {
                    return (
                        <span>{Util.doubleFormat(parseFloat(record.profitAccount/100).toFixed(2))}</span>
                    )
                }
            },{
                title: '合同详情',
                dataIndex: 'useNo',
                key: 'useNo',
                onCellClick: (record, event) => {
                    const {oid} = record;
                    hashHistory.push("/ordertradeinfo/"+oid);
                },
                render: (text, record) => {
                    return (
                        <span className="trade_rec_check">查看</span>
                    )
                }
            }
        ];
        const listInfo = (null == this.state.listInfo || this.state.listInfo.length == 0) ? [] : this.state.listInfo;
        return (
            <div className="trade_rec_box">
                <div className="trade_rec_box_tab"></div>
                <span className={this.state.status==""? "trade_rec_tabBox_span_active" :"trade_rec_tabBox_span"} onClick={this.whole.bind(this)}>全部</span>
                <span className={this.state.status=="3"? "trade_rec_tabBox_span_active" :"trade_rec_tabBox_span"} onClick={this.pending.bind(this)}>未完成</span>
                <span className={this.state.status=="4"? "trade_rec_tabBox_span_active" :"trade_rec_tabBox_span"} onClick={this.already.bind(this)}>已完成</span>
                {/*搜索*/}
                <div className="trade_loan_set_search clear">
                    <div className="trade_loan_set_searchcal">
                        <span className="trade_rec_tab1">日期：</span>
                        <DatePicker format="YYYY-MM-DD" onChange={value => this.setStartDate(value)} disabledDate={this.disabledStartDate}/>
                        <span className="trade_rec_tab2">至</span>
                        <DatePicker format="YYYY-MM-DD" onChange={value => this.setEndDate(value)}   disabledDate={this.disabledEndDate} />
                    </div>
                    <div className="trade_loan_set_searchBtn">
                        <span className="trade_loan_set_searchBtn_span" onClick={this.search.bind(this)}><i className="trade_loan_set_searchBtn_i"></i>搜索</span>
                        <span className="trade_loan_set_searchHint">{this.state.hint}</span>
                    </div>
                    <div className="trade_loan_set_searchInp">
                        {/*<span className="trade_loan_set_searchInp_sp">企业名称：</span>*/}
                        <InputBox className="trade_loan_set_searchInp_inp" space={20} ref={"search"} style={this.style.input} defaultvalute="请输入销售合同编号"
                                  maxlength={22} bluron={this.bluron.bind(this, "search")}
                                  focuson={this.focuson.bind(this,"search")}/>
                    </div>
                </div>
                <Table
                    columns={columns}
                    dataSource={listInfo}
                    pagination={false}
                    rowKey={record => record.oid}
                    style={{width: '100%'}}
                    className="order_table"
                    bordered
                    loading={this.state.loading}
                />
                <Pagination eachSize={this.state.pageSize} dataSize={this.state.totalResult} onSure={this.onSure.bind(this)} ref={'pagination'}/>
            </div>
        )
    }
}
